﻿using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using StudentManagementSystem.DatabaseConn;
using StudentManagementSystem.Dtos;
using StudentManagementSystem.Services;

namespace StudentManagementSystem
{
    public class Startup
    {
        public IConfiguration _Configuration { get; }


        /// <summary>
        /// 初始化 Startup 类，并接收 IConfiguration 实例。
        /// 通过依赖注入（DI）将配置信息传递给 Startup 类。
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration)
        {
            _Configuration = configuration;
        }



        /// <summary>
        /// 注册服务到依赖注入容器（默认是 .NET Core 内置的 DI 容器）
        /// </summary>
        /// <param name="services"></param>
        /// <exception cref="Exception"></exception>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(setup =>
            {
                // 检验请求的格式和框架支持的格式是否兼容，比如请求要求xml格式返回，但目前支持json格式，就会报406错误
                setup.ReturnHttpNotAcceptable = true;

                //手动添加返回（即输出）的格式,这种是旧版写法（0）
                //setup.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());

                //手动设置默认返回格式，这句可以把程序改为默认返回application/xml格式
                //setup.OutputFormatters.Insert(0, new XmlDataContractSerializerOutputFormatter());
            }).AddXmlDataContractSerializerFormatters()
            .ConfigureApiBehaviorOptions(setup =>
            {//配置错误信息
                setup.InvalidModelStateResponseFactory = context =>
                {
                    var problemDetatils = new ValidationProblemDetails() 
                    {
                        Type = "http://ww.baidu.com",
                        Title = "有错误！！！",
                        Status = StatusCodes.Status422UnprocessableEntity,
                        Detail = "请看详细信息",
                        Instance = context.HttpContext.Request.Path
                    };
                    problemDetatils.Extensions.Add("traced",context.HttpContext.TraceIdentifier);
                    return new UnprocessableEntityObjectResult(problemDetatils);
                };
            }); //这种是3.0版本后新版写法（0），输入输出都加上了


            // 关键：禁用自动模型验证
            // 如果不加上这个服务，控制器中各种方法的参数都要求输入，
            // 加上这个就是可选的了，可以输入，也可以不输入
            services.Configure<ApiBehaviorOptions>(options =>
            {
                options.SuppressModelStateInvalidFilter = false;
            });

            services.AddAutoMapper(typeof(AssemblyMarker).Assembly);
            //services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());


            services.AddScoped<ICompanyRepository, CompanyRepository>();
            services.AddDbContext<MysqlDbContext>(options =>
            {
                options.UseMySql(
                "Server=localhost;Database=efdemo;User=root;Password=123456;",
                ServerVersion.AutoDetect("Server=localhost;Database=efdemo;User=root;Password=123456;")
                );
            });
        }


        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(appBuilder =>
                {
                    appBuilder.Run(async context =>
                    {
                        context.Response.StatusCode = 500;
                        await context.Response.WriteAsync("UnExcept Error!");
                    });
                });
            }
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
